package com.zx.map.wx;

import com.zx.map.wx.bean.WxOauthBean;
import com.zx.platform.utils.HttpClientCommon;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 14-3-16 Time: 下午6:33 To
 * change this template use File | Settings | File Templates.
 */
public class WxOauthHelper {

	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(WxOauthHelper.class);

	private final static String URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	private final static String BASEINFO = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
	public final static String APPID = "wx85c32b6dc59c9e5f";
	public final static String APPSECURITY = "340fcc68d68dafe0339f72de9dff3c6e";

	public static String getOpenId(String code, String appId, String appSecurity) {
		// 初始内容初始化
		try {
			log.info("  oauth2.0 return code:" + code);
			Map<String, String> params = new HashMap<String, String>();
			params.put("appid", appId);
			params.put("secret", appSecurity);
			params.put("code", code);
			params.put("grant_type", "authorization_code");
			HttpClientCommon clientCommon = new HttpClientCommon();
			WxOauthBean wxOauthBean = clientCommon.getResult(WxOauthBean.class, URL, params);
			log.info("openid " + ToStringBuilder.reflectionToString(wxOauthBean));
			return wxOauthBean.getOpenid();
		} catch (Exception e) {
			log.error("内部异常", e);
			return null;
		}
	}

	public static String getOpenId(String code) {
		// 初始内容初始化
		return getOpenId(code, APPID, APPSECURITY);
	}


}
